package com.jin.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jin.common.utils.HttpUtils;
import com.jin.common.utils.R;
import com.jin.gulimall.auth.feign.MemberFeignService;
import com.jin.common.vo.MemberRespVo;
import com.jin.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code")String code, HttpSession session) throws Exception {
        //换取token所需的这些信息要用后端进行封装，这样安全保密
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "1652759784");
        map.put("client_secret", "b7e68670e9e92565769a9536e3789d59");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        //1.根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String,String>(), null, map);
        //2.处理response
        if(response.getStatusLine().getStatusCode()==200){
            //获取accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前的社交用户了，登录或注册这个用户
            R r = memberFeignService.oauthLogin(socialUser);
            if(r.getCode()==0){
                //成功
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录的用户为:{}"+data.toString());
                //第一次使用session;tomcat服务器会命令浏览器保存卡号，JSESSIONID这个cookies;
                //以后浏览器访问哪个网站就会带上这个网站的cookies
                //子域之间gulimall.com auth.gulimall.com order.gulimall.com
                //发卡的时候(指定域名为父域名)，即使是子域名系统发的卡，也能让父域直接使用
                session.setAttribute("loginUser",data);
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else{
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
